package com.getpebble.android.common.model;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ObjectUtil;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.model.PblDataModel.Column;
import com.getpebble.android.common.model.PblDataModel.Column.Type;
import com.getpebble.android.notifications.model.PblNotification;
import com.getpebble.android.util.SQLUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.UnsignedInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class PblNotificationModel extends PblDataModel {
    private static final String[] ALL_COLUMNS = new String[]{"notification_id", "package_name", "android_notification_id", "tag", "key", "text", "group_key", "is_summary", "timestamp_millis", "removed_timestamp_millis"};
    public static final long MAX_STORED_NOTIFICATION_AGE_MILLIS = TimeUnit.DAYS.toMillis(1);
    public static final Uri TABLE_URI = PblContentProviderUtil.getTableUri("notifications");
    private static final String TAG = PblNotificationModel.class.getSimpleName();

    public static class Record {
        public final int androidNotificationId;
        public final String androidNotificationKey;
        public final String androidNotificationTag;
        public final String androidPackageName;
        public final String groupKey;
        public final boolean isSummary;
        public final UnsignedInteger notificationId;
        public final long removedTimestampMillis;
        public final String text;
        public final long timestampMillis;

        public Record(UnsignedInteger notificationId, String packageName, int androidNotificationId, String androidNotificationTag, String androidNotificationKey, String text, String groupKey, boolean isSummary, long timestampMillis, long removedTimestampMillis) {
            this.notificationId = notificationId;
            this.androidPackageName = packageName;
            this.androidNotificationId = androidNotificationId;
            this.androidNotificationTag = androidNotificationTag;
            this.androidNotificationKey = androidNotificationKey;
            this.text = text;
            this.groupKey = groupKey;
            this.isSummary = isSummary;
            this.timestampMillis = timestampMillis;
            this.removedTimestampMillis = removedTimestampMillis;
        }

        public String toString() {
            return "PblNotificationRecord{notificationId=" + this.notificationId + ", androidPackageName='" + this.androidPackageName + '\'' + ", androidNotificationId=" + this.androidNotificationId + ", androidNotificationTag='" + this.androidNotificationTag + '\'' + ", androidNotificationKey='" + this.androidNotificationKey + '\'' + ", text='" + this.text + '\'' + ", groupKey='" + this.groupKey + '\'' + ", isSummary='" + this.isSummary + '\'' + ", timestampMillis='" + this.timestampMillis + '\'' + ", removedTimestampMillis='" + this.removedTimestampMillis + '\'' + '}';
        }

        public String toSanitizedString() {
            return "PblNotificationRecord{notificationId=" + this.notificationId + ", androidPackageName='" + this.androidPackageName + '\'' + ", androidNotificationId=" + this.androidNotificationId + ", androidNotificationTag='" + this.androidNotificationTag + '\'' + ", androidNotificationKey='" + this.androidNotificationKey + '\'' + ", text (obfuscated) = '" + ObjectUtil.hash(this.text) + '\'' + ", groupKey='" + this.groupKey + '\'' + ", isSummary='" + this.isSummary + '\'' + ", timestampMillis='" + this.timestampMillis + '\'' + ", removedTimestampMillis='" + this.removedTimestampMillis + '\'' + '}';
        }
    }

    public PblNotificationModel() throws IllegalArgumentException {
        super("notifications");
        addColumn(new Column(Type.INTEGER, "notification_id"));
        addColumn(new Column(Type.STRING, "package_name"));
        addColumn(new Column(Type.INTEGER, "android_notification_id"));
        addColumn(new Column(Type.STRING, "tag"));
        addColumn(new Column(Type.STRING, "key"));
        addColumn(new Column(Type.STRING, "text"));
        addColumn(new Column(Type.STRING, "group_key"));
        addColumn(new Column(Type.INTEGER, "is_summary"));
        addColumn(new Column(Type.INTEGER, "timestamp_millis"));
        addColumn(new Column(Type.INTEGER, "removed_timestamp_millis"));
    }

    public static List<String> addPropertyColumnCommands() {
        return ImmutableList.of(SQLUtil.getAddColumnCommand("notifications", new Column(Type.STRING, "text")), SQLUtil.getAddColumnCommand("notifications", new Column(Type.STRING, "group_key")), SQLUtil.getAddColumnCommand("notifications", new Column(Type.INTEGER, "is_summary")), SQLUtil.getAddColumnCommand("notifications", new Column(Type.INTEGER, "timestamp_millis")));
    }

    public static List<String> addRemovedColumnCommands() {
        return ImmutableList.of(SQLUtil.getAddColumnCommand("notifications", new Column(Type.INTEGER, "removed_timestamp_millis")));
    }

    public static void insert(ContentResolver contentResolver, Record record) throws IllegalArgumentException {
        if (contentResolver == null) {
            throw new IllegalArgumentException("Cannot insert record with null content resolver");
        }
        Trace.debug(TAG, "Inserting notification record: " + record.toSanitizedString());
        ContentValues contentValues = new ContentValues(4);
        contentValues.put("notification_id", Long.valueOf(record.notificationId.longValue()));
        contentValues.put("package_name", record.androidPackageName);
        contentValues.put("android_notification_id", Integer.valueOf(record.androidNotificationId));
        contentValues.put("tag", record.androidNotificationTag);
        contentValues.put("key", record.androidNotificationKey);
        contentValues.put("text", record.text);
        contentValues.put("group_key", record.groupKey);
        contentValues.put("is_summary", Integer.valueOf(record.isSummary ? 1 : 0));
        contentValues.put("timestamp_millis", Long.valueOf(record.timestampMillis));
        contentValues.put("removed_timestamp_millis", Long.valueOf(record.removedTimestampMillis));
        contentResolver.insert(TABLE_URI, contentValues);
    }

    private static Record getRecordFromCursor(Cursor cursor) {
        return new Record(UnsignedInteger.valueOf(cursor.getLong(cursor.getColumnIndex("notification_id"))), cursor.getString(cursor.getColumnIndex("package_name")), cursor.getInt(cursor.getColumnIndex("android_notification_id")), cursor.getString(cursor.getColumnIndex("tag")), cursor.getString(cursor.getColumnIndex("key")), cursor.getString(cursor.getColumnIndex("text")), cursor.getString(cursor.getColumnIndex("group_key")), cursor.getInt(cursor.getColumnIndex("is_summary")) > 0, cursor.getLong(cursor.getColumnIndex("timestamp_millis")), cursor.getLong(cursor.getColumnIndex("removed_timestamp_millis")));
    }

    public static Record findNotification(String androidPackageName, int androidNotificationId, String androidNotificationTag, String androidNotificationKey, ContentResolver contentResolver) {
        if (contentResolver == null) {
            throw new IllegalArgumentException("Cannot fetch stored notifications with null content resolver");
        }
        StringBuilder selection = new StringBuilder();
        ArrayList<String> selectionArgs = new ArrayList();
        selection.append("package_name = ? AND tag");
        selectionArgs.add(androidPackageName);
        if (androidNotificationTag == null) {
            selection.append(" IS NULL ");
        } else {
            selection.append(" = ? ");
            selectionArgs.add(androidNotificationTag);
        }
        selection.append(" AND key");
        if (androidNotificationKey == null) {
            selection.append(" IS NULL ");
        } else {
            selection.append(" = ? ");
            selectionArgs.add(androidNotificationKey);
        }
        selection.append(" AND android_notification_id = ?");
        selectionArgs.add(String.valueOf(androidNotificationId));
        ContentResolver contentResolver2 = contentResolver;
        Cursor cursor = contentResolver2.query(TABLE_URI, ALL_COLUMNS, selection.toString(), (String[]) selectionArgs.toArray(new String[selectionArgs.size()]), null);
        if (cursor == null) {
            return null;
        }
        if (cursor.moveToFirst()) {
            Record record = getRecordFromCursor(cursor);
            cursor.close();
            return record;
        }
        cursor.close();
        return null;
    }

    public static List<Record> findNotifications(String androidPackageName, ContentResolver contentResolver) {
        List<Record> notifications = new ArrayList();
        String selection = "package_name = ?";
        ContentResolver contentResolver2 = contentResolver;
        Cursor cursor = contentResolver2.query(TABLE_URI, ALL_COLUMNS, "package_name = ?", new String[]{androidPackageName}, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                notifications.add(getRecordFromCursor(cursor));
            }
            cursor.close();
        }
        return notifications;
    }

    public static Record findNotification(UnsignedInteger notificationId, ContentResolver contentResolver) {
        if (contentResolver == null) {
            throw new IllegalArgumentException("Cannot fetch stored notifications with null content resolver");
        }
        String selection = "notification_id = ?";
        ContentResolver contentResolver2 = contentResolver;
        Cursor cursor = contentResolver2.query(TABLE_URI, ALL_COLUMNS, "notification_id = ?", new String[]{String.valueOf(notificationId.longValue())}, null);
        if (cursor == null) {
            return null;
        }
        if (cursor.moveToFirst()) {
            Record record = getRecordFromCursor(cursor);
            cursor.close();
            return record;
        }
        cursor.close();
        return null;
    }

    public static Record findPreviousNotification(String packageName, String text, String androidNotificationKey, ContentResolver contentResolver, boolean checkRemovedTimestamp, PblNotification pblNotification) {
        if (contentResolver == null) {
            throw new IllegalArgumentException("Cannot fetch stored notifications with null content resolver");
        }
        String textSelection;
        Trace.debug(TAG, "findPreviousNotification package = '" + packageName + "' text (obfuscated) = '" + ObjectUtil.obfuscate(text) + "' androidNotificationKey = '" + androidNotificationKey + "'");
        String groupKeySelection = "";
        ArrayList<String> selectionArgs = new ArrayList();
        selectionArgs.add(packageName);
        if (text == null) {
            textSelection = "";
        } else {
            textSelection = " AND text = ?";
            selectionArgs.add(text);
        }
        if (androidNotificationKey != null) {
            groupKeySelection = " AND key = ?";
            selectionArgs.add(androidNotificationKey);
        }
        String removedTimestampSelection = "";
        if (checkRemovedTimestamp) {
            removedTimestampSelection = "AND (removed_timestamp_millis = 0 OR removed_timestamp_millis > ?)";
            selectionArgs.add(String.valueOf(System.currentTimeMillis() - pblNotification.getTypeRemovedThresholdMillis()));
        }
        String order = "timestamp_millis DESC";
        ContentResolver contentResolver2 = contentResolver;
        Cursor cursor = contentResolver2.query(TABLE_URI, ALL_COLUMNS, "package_name = ?" + textSelection + groupKeySelection + removedTimestampSelection, (String[]) selectionArgs.toArray(new String[selectionArgs.size()]), "timestamp_millis DESC");
        if (cursor == null) {
            return null;
        }
        if (cursor.moveToFirst()) {
            Record record = getRecordFromCursor(cursor);
            cursor.close();
            return record;
        }
        cursor.close();
        return null;
    }

    public static void purgeNotificationsForAllPackages(ContentResolver contentResolver) {
        String where = "timestamp_millis < ?";
        String[] selectionArgs = new String[]{String.valueOf(System.currentTimeMillis() - MAX_STORED_NOTIFICATION_AGE_MILLIS)};
        Trace.debug(TAG, "Deleting all records older than " + (System.currentTimeMillis() - MAX_STORED_NOTIFICATION_AGE_MILLIS));
        contentResolver.delete(TABLE_URI, "timestamp_millis < ?", selectionArgs);
    }

    public static void markRemovedNotificationsForKey(ContentResolver contentResolver, String pkg, String key) {
        String where = "package_name = ? AND key = ?";
        String[] selectionArgs = new String[]{pkg, key};
        Trace.debug(TAG, "Marking removed all records for pkg = '" + pkg + "' key = '" + key + "'");
        ContentValues values = new ContentValues();
        values.put("removed_timestamp_millis", Long.valueOf(System.currentTimeMillis()));
        contentResolver.update(TABLE_URI, values, "package_name = ? AND key = ?", selectionArgs);
    }
}
